package models

// 合服一定要先清了这里的数据

import (
	"github.com/jinzhu/gorm"
	"kop/libs/database"
	"kop/modules/maid/entity"
	"kop/util/cd"
	"time"
)

const KidCD = time.Minute * 30 // 调戏次数恢复CD

func GetGardenMaids(roleID int32) []*entity.GardenMaid {

	var data []*entity.GardenMaid
	if err := database.DB.Find(&data, "role_id = ?", roleID).Error; err != nil {
		panic(err)
	}

	var res = make([]*entity.GardenMaid, 0, len(data))
	for _, v := range data {

		if v.TimeOver() {
			_ = RemoveGardenMaid(v)
		} else {
			res = append(res, v)
		}
	}

	return res
}

func GetByRoleIDMasterID(roleID, masterID int32) (*entity.GardenMaid, bool) {

	var data = entity.GardenMaid{
		RoleID:   roleID,
		MasterID: masterID,
	}

	if err := database.DB.First(&data).Error; err != nil {
		if err == gorm.ErrRecordNotFound {
			return nil, false
		} else {
			panic(err)
		}
	}

	return &data, true
}

// 被抢走的侍女
//func GetGardenMaidByMasterID(masterID, maidID int32) (*entity.GardenMaid, bool) {
//
//	var data = entity.GardenMaid{
//		MasterID: masterID,
//		MaidID:  maidID,
//	}
//
//	if err := database.DB.First(&data).Error; err != nil {
//		if err == gorm.ErrRecordNotFound {
//			return nil, false
//		} else {
//			panic(err)
//		}
//	}
//
//	return &data, true
//}

func GetLostMaids(masterID int32) map[int32]*entity.GardenMaid {

	var data []*entity.GardenMaid
	if err := database.DB.Find(&data, "master_id = ?", masterID).Error; err != nil {
		panic(err)
	}

	var m = make(map[int32]*entity.GardenMaid, len(data))
	for _, v := range data {

		if v.TimeOver() {
			database.DB.Delete(&v)
		} else {
			m[v.MaidID] = v
		}
	}

	return m
}

func CreateGardenMaid(data *entity.GardenMaid) error {

	return database.DB.Create(data).Error
}

func SaveGardenMaid(dB *gorm.DB, data *entity.GardenMaid) error {

	return dB.Save(data).Error
}

func RemoveGardenMaid(data *entity.GardenMaid) error {

	return database.DB.Delete(data).Error
}

func GetGarden(roleID int32) *entity.Garden {

	var data = entity.Garden{RoleID: roleID, Seat: 1, Time: cd.NewCD(KidCD, 10).SetNum(10)}
	if err := database.DB.FirstOrCreate(&data).Error; err != nil {
		panic(err)
	}

	return &data
}

func SaveGarden(dB *gorm.DB, data *entity.Garden) error {

	return dB.Save(data).Error
}
